package com.itheima.controller.system;

import com.github.pagehelper.PageInfo;
import com.itheima.controller.BeanServlet;
import com.itheima.domain.system.Dept;
import com.itheima.domain.system.User;
import com.itheima.service.system.DeptService;
import com.itheima.service.system.Impl.DeptServiceImpl;
import com.itheima.service.system.Impl.UserServiceImpl;
import com.itheima.service.system.UserService;
import com.itheima.utils.BeanUtil;
import com.mysql.jdbc.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;

/**
 * @param
 * @return
 */
@WebServlet("/system/user/*")
public class UserServlet extends BeanServlet {
//创建业务层对象复用
    UserService service=new UserServiceImpl();
    protected void save(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException  {
        //调用工具类处理前端传递的数据
        User user = BeanUtil.fillBean(req, User.class, "yyyy-MM-dd");
        //调用业务层的新增方法
        int i =service.save(user);
        //新增后走分页查询跳转
        this.findByPage(req,resp);
    }
    protected void findAllDept(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //创建部门业务层对象
        DeptService deptService=new DeptServiceImpl();
        //获取所有部门集合
        List<Dept> deptList = deptService.findAllDept();
        //将集合存进作用域
        req.setAttribute("deptList",deptList);
        //转发到用户添加页面，把部门集合数据带过去供下拉框显示
        req.getRequestDispatcher("/pages/system/user/add.jsp").forward(req,resp);
    }
    protected void findByPage(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //设置分页初始参数
        int pageNum=1;
        int pageSize=5;
        String pageNumStr = req.getParameter("page");
        String pageSizeStr = req.getParameter("pageSize");
        if (!StringUtils.isNullOrEmpty(pageNumStr)) {
            pageNum = Integer.parseInt(pageNumStr);
        }
        if (!StringUtils.isNullOrEmpty(pageSizeStr)) {
            pageSize = Integer.parseInt(pageSizeStr);
        }
       //调用业务层查询所有方法
        List<User> list=service.findByPage(pageNum,pageSize);
        System.out.println("list = " + list);
        //分页对象走起
        PageInfo<User> page = new PageInfo<>(list);
        //将数据存进作用域
        HttpSession session = req.getSession();
        session.setAttribute("page",page);
        //重定向到前端页面
        resp.sendRedirect(req.getContextPath()+"/pages/system/user/list.jsp");
    }
}
